import GameUtil from "@/utils/GameUtil";
import OtherLivePlayerObj from "@/assets/js/player/OtherLivePlayerObj";
import Store from "@/store";

export default class MultiplePlayerSocket{
    constructor(context) {
        this.context=context;
        this.ws= new WebSocket("ws://localhost:8080/game");
        this.start();
    }
    start(){
        this.receive();
    }
    onDestroy(){
        this.ws.onclose=()=>{
            let that=this;
            this.ws.send(JSON.stringify({
                "type":"1",
                "data":{
                    "uuid":that.uuid,
                    "username":username,
                    "photo":photo,
                }
            }))
        }
    }
    sendCreatePlayer(username,photo){
        let that=this;
        this.ws.send(JSON.stringify({
            "type":"1",
            "data":{
                "uuid":that.uuid,
                "username":username,
                "photo":photo,
            }
        }))

    }
    receive () {
        let outer = this;
        this.ws.onmessage = function(e) {
            let data = JSON.parse(e.data);
            let type = data.type;
            if(type==2) return false;
            let uuid = data.data.uuid;
            if(uuid==outer.uuid) return false;
            if (type === 1) {
                let username= data.data.username;
                let photo = data.data.photo;
                outer.receiveCreatePlayer(uuid,username ,photo );
            }
        };
    }
    receiveCreatePlayer(uuid, username, photo){
        // TODO username
        let scale=Store.state.scale;
        let otherLivePlayerObj = new OtherLivePlayerObj(this.context,this.context.ctx.canvas.width/2/scale,0.5,0.05,0.15,photo,GameUtil.getRandomColor(Math.random()));
        otherLivePlayerObj.uuid=uuid;
        this.context.players.push(otherLivePlayerObj);
    }
}
